package com.sh.pangea.dsa.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SlidingDrawer;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.LargeValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.sh.lib.dsa.bean.AuthDetailInfo;
import com.sh.lib.dsa.bean.SummaryInfo;
import com.sh.lib.dsa.bean.UserWxDetailInfo;
import com.sh.lib.dsa.bean.analyzeresult.AnalyzeResultLinear;
import com.sh.lib.dsa.bean.analyzeresult.LinearItem;
import com.sh.lib.dsa.bean.filter.DataFilter;
import com.sh.lib.dsa.bean.filter.FilterCondition;
import com.sh.lib.dsa.bean.filter.FilterType;
import com.sh.lib.dsa.callback.AnalyzeLinearListener;
import com.sh.lib.dsa.callback.DataFilterListener;
import com.sh.lib.dsa.callback.ListListener;
import com.sh.pangea.dsa.R;
import com.sh.pangea.dsa.Utils.AnalyzeResultUtil;
import com.sh.pangea.dsa.Utils.AnalyzeStringUtil;
import com.sh.pangea.dsa.Utils.TransitionAnalyzeResultUtil;
import com.sh.pangea.dsa.Utils.XYMarkerView;
import com.sh.pangea.dsa.adapter.SingleTextAdapter;
import com.sh.pangea.dsa.bean.AnalyzeResult;
import com.sh.pangea.dsa.bean.MenuInfo;
import com.sh.pangea.dsa.observer.AnalyzeResultObservable;
import com.sh.pangea.dsa.observer.AnalyzeResultObserver;
import com.sh.pangea.dsa.view.HospitalDetailsDataItem;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.sh.pangea.dsa.R.id.tv_hospital_details;
import static com.sh.pangea.dsa.R.id.tx_01;
import static com.umeng.socialize.utils.Log.TAG;


/**
 * Created by TianGenhu on 2017/1/9.
 * 展示无线认证界面
 */

public class WirelessAuthenticationLineChart extends Activity implements AnalyzeResultObserver, View.OnClickListener {
    @BindView(tv_hospital_details)
    TextView tvHospital;
    @BindView(R.id.rl_select_hospital)
    RelativeLayout rlHospital;
    @BindView(R.id.ll_yest_day_info)
    LinearLayout llYestDayInfo;
    @BindView(R.id.tv_channel_line_chart)
    LineChart lineChart;
    @BindView(R.id.gv_date)
    GridView gvDate;
    @BindView(R.id.filter_head_img)
    ImageView filter_head_img;
    @BindView(R.id.filter_background)
    View filter_background;
    @BindView(R.id.filter_bt_restart)
    Button restart;
    @BindView(R.id.filter_bt_submit)
    Button submit;
    //    @BindView(R.id.tv_more_data)
//    TextView tvMoreData;
    @BindView(R.id.gv_view_type)
    GridView gvViewType;

    SingleTextAdapter dateAdapter;
    SingleTextAdapter viewTypeAdapter;
    SingleTextAdapter hospitalAdapter;

    @BindView(R.id.filter_slidingdrawer)
    SlidingDrawer slidingdrawer;
    @BindView(R.id.gv_hospital)
    GridView gvHospital;
    @BindView(R.id.rl_hospital)
    RelativeLayout rlHospitalGroup;
    @BindView(R.id.rl_view_type)
    RelativeLayout rlViewType;
    @BindView(tx_01)
    TextView tvViewtyp;

    @BindView(R.id.expandablelistview)
    ExpandableListView expandablelistview;

    /**
     * 返回
     **/
    @OnClick(R.id.analyze_back)
    public void onBackClick(View view) {
        this.finish();
    }

    /**
     * 重置
     */
    @OnClick(R.id.analyze_reset)
    public void onResetClick(View view) {
        initScreenStateState();
        submitData();
    }

    /**
     * 分享
     */
    @OnClick(R.id.analyze_share)
    public void onShareClick(View view) {
        //TODO 实现分享
        Log.i(TAG, "onShareClick: ");
        if (lineChart != null) {
            lineChart.saveToGallery("thumbnail", 100);
            Bitmap bit = lineChart.getChartBitmap();
            ShareAction shareAction = new ShareAction(WirelessAuthenticationLineChart.this);
            shareAction.withTitle(nameGraph);
            // TODO: 2016/12/26 暂时注释掉 ，需要修改
            shareAction.withText(/*mAnalyzeResult.getNameGraph()*/"");
            shareAction.withTargetUrl("http://www.skyworth-hightong.com");
            if (bit != null) {
                shareAction.withMedia(new UMImage(this.getApplicationContext(), bit));
            }
            shareAction.setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener).open();

        } else {
            Log.i(TAG, "onShareClick: lineChart is null ");
        }
    }

    private final UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA share_media) {
            Log.i(TAG, "分享返回值  onResult: " + share_media);
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            Log.i(TAG, "分享失败 onError: " + share_media);
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            Log.i(TAG, "取消分享  onCancel: " + share_media);
        }
    };


    private String viewType; //界面显示的类型  1  无线认证日走势图 2 公众号用户  3无限认证

    private String selectDate;
    private int selectViewType; // viewtype =2时: 0新关注人数 1：取消关注人数 2：净增关注人数 3：累计关注人数
    private String selectHospitalCode;

    List<FilterCondition> comboxList;
    private ArrayList<String> groupTime = new ArrayList<>(); //详细数据ExpandableListView的父组件数据
    private Map<String, List<String>> childDataMap = new HashMap<>();
    private List<FilterCondition> hospitalComboxList;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AnalyzeResultObservable.getInstance().registerObserver(this);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //一直显示手机状态栏
        this.findViewById(Window.ID_ANDROID_CONTENT);
        setContentView(R.layout.activity_wireless_authentication_line_chart);
        context = this;
        getIntetn();
        showViewType();
        initView();
        getData();
    }

    private void getData() {
        switch (viewType) {
            case "1":
                getWifiData();
                break;
            case "2":
                getWeiXinData();
                break;
            case "3":
                getHospitalWifiData();
                break;
        }
    }


    ListListener listListener = new ListListener<AuthDetailInfo>() {
        @Override
        public void onSuccess(List<AuthDetailInfo> list) {
            getExpandableData(list);
            expandablelistview.setAdapter(new WifiExpandableListView());
        }

        @Override
        public void onPrepare(String s) {

        }

        @Override
        public void onFail(int i, String s) {

        }
    };

    private void queryTrendAuthDayList() {
        AnalyzeResultUtil.getInstance(this).queryTrendAuthDayList(selectDate, listListener);
    }

    private void queryTrendUserWxList() {
        AnalyzeResultUtil.getInstance(this).queryTrendUserWxList(selectDate, new ListListener<UserWxDetailInfo>() {
            @Override
            public void onSuccess(List<UserWxDetailInfo> list) {
                getWXExpandableData(list);
                expandablelistview.setAdapter(new WifiExpandableListView());
            }

            @Override
            public void onPrepare(String s) {

            }

            @Override
            public void onFail(int i, String s) {

            }
        });
    }

    private void queryTrendAuthDayAreaList() {
        AnalyzeResultUtil.getInstance(this).queryTrendAuthDayAreaList(selectHospitalCode, selectDate, listListener);
    }


    private void getExpandableData(List<AuthDetailInfo> list) {
        for (int i = 0; i < list.size(); i++) {
            AuthDetailInfo authDetailInfo = list.get(i);
            String playDay = authDetailInfo.getPlayDay();
            groupTime.add(playDay);
            List<String> childData = new ArrayList<>();
            childData.add("放行次数:" + authDetailInfo.getNumsSuccess());
            childData.add("放行设备数:" + authDetailInfo.getNumsSuccessDev());
            childData.add("免认证次数:" + authDetailInfo.getNumsFree());
            childData.add("免认证设备数:" + authDetailInfo.getNumsFreeDev());
            childData.add("认证次数:" + authDetailInfo.getNumsTotal());
            childData.add("认证设备数:" + authDetailInfo.getNumsTotalDev());
            childData.add("认证成功次数比率:" + authDetailInfo.getRatePv());
            childData.add("认证成功设备比率:" + authDetailInfo.getRateUv());
            childData.add("人均放行次数:" + authDetailInfo.getPerPv());
            childData.add("人均认证次数:" + authDetailInfo.getPerUv());
            childData.add("新增设备数:" + authDetailInfo.getNumsAddDev());
            int numsAddUser = authDetailInfo.getNumsAddUser();
            if (numsAddUser != 0) {
                childData.add("新增用户数:" + authDetailInfo.getNumsAddUser());
            }

            childDataMap.put(playDay, childData);
        }

    }

    private void getWXExpandableData(List<UserWxDetailInfo> list) {
        for (int i = 0; i < list.size(); i++) {
            UserWxDetailInfo authDetailInfo = list.get(i);
            String playDay = authDetailInfo.getPlayDay();
            groupTime.add(playDay);
            List<String> childData = new ArrayList<>();
            childData.add("新关注人数:" + authDetailInfo.getNumsAttentionUser());
            childData.add("累积关注人数:" + authDetailInfo.getNumsAttentionUserSum());
            childData.add("取消关注人数:" + authDetailInfo.getNumsGiveupUser());
            childData.add("净增关注人数:" + authDetailInfo.getNumsNetUser());
            childDataMap.put(playDay, childData);
        }

    }

    private void getHospitalWifiData() {
        AnalyzeResultUtil.getInstance(this).queryTrendAuthDayAreaSelCondList(dataFilterListener);

    }

    ListListener summaryInfoListener = new ListListener<SummaryInfo>() {
        @Override
        public void onSuccess(List<SummaryInfo> list) {
            if (list != null) {
                addYestDayView(list);
            }
            handler.sendEmptyMessage(handler.QueryTrend);
        }

        @Override
        public void onPrepare(String s) {
        }

        @Override
        public void onFail(int i, String s) {
            if (viewType.equals("1")) {
                AnalyzeResultUtil.getInstance(context).queryTrendAuthDaySelCondList(dataFilterListener);
            } else if (viewType.equals("2")) {
                AnalyzeResultUtil.getInstance(context).queryTrendUserWxSelCondList(dataFilterListener);
            }
        }
    };
    DataFilterListener dataFilterListener = new DataFilterListener() {
        @Override
        public void onSuccess(DataFilter dataFilter) {
            initDateData(dataFilter);
            handler.sendEmptyMessage(handler.QueryTrendAuthDayYestDayInfo);
        }

        @Override
        public void onPrepare(String s) {
        }

        @Override
        public void onFail(int i, String s) {
        }
    };

    /**
     * @param dataFilter 筛选数据
     *                   获取到的筛选信息, 初始化筛选条件
     */
    private void initDateData(DataFilter dataFilter) {
        if (dataFilter != null) {
            List<?> dataList = dataFilter.getDataList();
            for (int i = 0; i < dataList.size(); i++) {
                FilterType filterType = (FilterType) dataList.get(i);
                if (filterType.getName().equals("instanceCode")) {
                    hospitalComboxList = filterType.getComboxList();
                    if (hospitalComboxList != null) {
                        hospitalAdapter.updata(hospitalComboxList);
                        setSelectHospital(0);
                    }
                } else if (filterType.getName().equals("timeRange")) {
                    FilterType filterType1 = (FilterType) dataList.get(i);
                    comboxList = filterType1.getComboxList();
                    selectDate = comboxList.get(0).getValue();
                    dateAdapter.updata(comboxList);
                }
                if (!viewType.equals("1")) {
                    List<FilterCondition> filterConditions = null;
                    if (viewType.equals("2")) {
                        filterConditions = set();
                    } else if (viewType.equals("3")) {
                        filterConditions = setHospitalData();
                    }
                    viewTypeAdapter.updata(filterConditions);
                    selectSetViewType(0);
                }
            }
        }
    }

    private void selectSetViewType(int post) {
        selectViewType = post;
        viewTypeAdapter.setSelect(post);
        FilterCondition condition = (FilterCondition) viewTypeAdapter.getItem(post);
        tvViewtyp.setText(condition.getName());
    }

    private List<FilterCondition> set() {
        List<FilterCondition> comboxList = new ArrayList<>();
        FilterCondition condition0 = new FilterCondition();
        condition0.setValue("0");
        condition0.setName("新关注人数");
        comboxList.add(condition0);
        FilterCondition condition1 = new FilterCondition();
        condition1.setValue("1");
        condition1.setName("取消关注人数");
        comboxList.add(condition1);
        FilterCondition condition2 = new FilterCondition();
        condition2.setValue("2");
        condition2.setName("净增关注人数");
        comboxList.add(condition2);
        FilterCondition condition3 = new FilterCondition();
        condition3.setValue("3");
        condition3.setName("累计关注人数");
        comboxList.add(condition3);
        return comboxList;
    }

    private List<FilterCondition> setHospitalData() {
        List<FilterCondition> comboxList = new ArrayList<>();
        FilterCondition condition0 = new FilterCondition();
        condition0.setValue("0");
        condition0.setName("认证设备数");
        comboxList.add(condition0);
        FilterCondition condition1 = new FilterCondition();
        condition1.setValue("1");
        condition1.setName("放行设备数");
        comboxList.add(condition1);
        FilterCondition condition2 = new FilterCondition();
        condition2.setValue("2");
        condition2.setName("新增设备数");
        comboxList.add(condition2);
        FilterCondition condition3 = new FilterCondition();
        condition3.setValue("3");
        condition3.setName("新增用户数");
        comboxList.add(condition3);
        return comboxList;
    }

    private void getWifiData() {
        AnalyzeResultUtil.getInstance(context).queryTrendAuthDaySelCondList(dataFilterListener); //获取筛选日期
    }

    private void getWeiXinData() {
        AnalyzeResultUtil.getInstance(context).queryTrendUserWxSelCondList(dataFilterListener); //获取公众号用户总览的查询条件列表

    }

    private void addYestDayView(List<SummaryInfo> list) {
        Log.i(TAG, list.size() + ">>>");
        for (int i = 0; i < list.size(); i++) {
            SummaryInfo summaryInfo = list.get(i);
            HospitalDetailsDataItem item = new HospitalDetailsDataItem(this);
            item.update(summaryInfo);
            llYestDayInfo.addView(item);
        }
    }

    private MenuInfo groupInfo;
    private MenuInfo childInfo;

    private void getIntetn() {
        Intent intent = this.getIntent();
        MenuInfo parentInfo = (MenuInfo) intent.getSerializableExtra("parentInfo");
        groupInfo = (MenuInfo) intent.getSerializableExtra("groupInfo");
        childInfo = (MenuInfo) intent.getSerializableExtra("childInfo");
        Log.i(TAG, "getIntetn  : " + parentInfo + "   " + groupInfo + "  " + childInfo);
    }

    private void initView() {
        ButterKnife.bind(this);
        tvHospital.setOnClickListener(this);
        slidingdrawer.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() {
            @Override
            public void onDrawerClosed() {
                setImageState(R.mipmap.bg_home_poster_content, R.mipmap.icon_screen_up);
            }
        });
        slidingdrawer.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener() {
            @Override
            public void onDrawerOpened() {
                slidingdrawer.getContent().bringToFront();
                setImageState(WirelessAuthenticationLineChart.this.getResources().getColor(R.color.transparent), R.color.transparent);
            }
        });
        filter_background.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (slidingdrawer != null) {
                    slidingdrawer.close();
                }
            }
        });
        dateAdapter = new SingleTextAdapter(this);
        if (viewType.equals("2") || viewType.equals("3")) {
            rlViewType.setVisibility(View.VISIBLE);
            viewTypeAdapter = new SingleTextAdapter(this);
            gvViewType.setAdapter(viewTypeAdapter);
            gvViewType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    selectSetViewType(position);
                }
            });
        }else{
            tvViewtyp.setText("无线认证走势图");
        }
        if (viewType.equals("3")) {
            rlHospitalGroup.setVisibility(View.VISIBLE);
            hospitalAdapter = new SingleTextAdapter(this);
            gvHospital.setAdapter(hospitalAdapter);
            gvHospital.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    setSelectHospital(position);
                }
            });
        }
        gvDate.setAdapter(dateAdapter);
        gvDate.setNumColumns(4);
        gvDate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                initSelectDateState(position);
            }
        });
        restart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initScreenStateState();
            }
        });
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (viewType.equals("1")) {
//                    queryTrendAuthDayGraph(selectDate);
//                } else if (viewType.equals("2")) {
//                    queryTrendUserWxGraph();
//                } else if (viewType.equals("3")) {
//                    queryTrendAuthDayAreaYestDayInfo(selectHospitalCode);
//                }
                submitData();

            }
        });
//        btMoreData.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                goMoreData(viewType);
//            }
//        });
        expandablelistview.setGroupIndicator(getResources().getDrawable(R.drawable.expandablelistview));
    }

    private void setSelectHospital(int post) {
        if (hospitalComboxList != null) {
            FilterCondition filterCondition = hospitalComboxList.get(post);
            selectHospitalCode = filterCondition.getValue();
            hospitalAdapter.setSelect(post);
        }
    }


    private void initSelectDateState(int position) {
        if (comboxList != null && comboxList.size() > position) {
            FilterCondition filterCondition = comboxList.get(position);
            selectDate = filterCondition.getValue();
            dateAdapter.setSelect(position);
        }
    }

    private void initScreenStateState() {
        initSelectDateState(0);
        if (viewType.equals("2") || viewType.equals("3")) {
            selectSetViewType(0);
            if (viewType.equals("3")) {
                setSelectHospital(0);
            }

        }
    }

    private void submitData() {
        switch (viewType) {
            case "1":
                queryTrendAuthDayGraph(selectDate);
                break;
            case "2":
                queryTrendUserWxGraph();
                break;
            case "3":
                queryTrendAuthDayAreaYestDayInfo(selectHospitalCode);
                break;
        }
        if (slidingdrawer != null) {
            slidingdrawer.close();
        }
    }

    /**
     * 设置头题头图片的背景及资源
     */
    private void setImageState(int bgRes, int imgRes) {
        filter_head_img.setBackgroundResource(bgRes);
        filter_head_img.setImageResource(imgRes);
    }

    private void showViewType() {
        if (groupInfo.getId().equals("S0")) { //总览
            if (childInfo.getId().equals("A1")) { //无线认证日走势图
                viewType = "1";
            } else if (childInfo.getId().equals("B1")) { //公众号用户
                viewType = "2";
            }
        } else if (groupInfo.getId().equals("S4")) { //按医院
            viewType = "3";
        }
    }

    private final IAxisValueFormatter mIAxisValueFormatter_X = new IAxisValueFormatter() {

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            String a = "";
            if (xForGraph != null) {
                a = xForGraph.get(Math.min(Math.max((int) value, 0), xForGraph.size() - 1));
            }
            return a;
        }

        @Override
        public int getDecimalDigits() {
            return 0;
        }
    };
    private final DecimalFormat mFormat = new DecimalFormat("###,###,###,##0.0");
    private final IAxisValueFormatter mIAxisValueFormatter_Y_right = new IAxisValueFormatter() {
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            String s;
            if (has_K) {
                s = mFormat.format(value / 1000) + " K";
            } else {
                s = mFormat.format(value);
            }
            return s;
        }

        @Override
        public int getDecimalDigits() {
            return 0;
        }
    };
    private boolean has_K = false;
    private final IAxisValueFormatter mIAxisValueFormatter_Y = new IAxisValueFormatter() {
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            String s;
            if (has_K) {
                s = mFormat.format(value / 1000) + " K";
            } else {
                s = mFormat.format(value);
            }
            return s;
        }

        @Override
        public int getDecimalDigits() {
            return 0;
        }
    };

    /**
     * 接收接口返回的数据
     */
    @Override
    public void onAnalyzeResult(int code, String error, AnalyzeResult analyzeResult) {
        initLineData(analyzeResult);
        setLineChart(lineChart);
    }


    private void showIconType(List<LinearItem> linearItems, String nameGraph) {
        if (linearItems != null && linearItems.size() > 0) {
            Log.i("TGH", "showIconType  : " + linearItems);
            generateDataLine(linearItems, nameGraph);
        } else {
            Log.i(TAG, "showIconType: linearItems is null");
        }
    }

    public void generateDataLine(List<LinearItem> linearItems, String nameGraph) {
        if (linearItems != null && linearItems.size() > 0) {
            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
            LineDataSet set1;
            for (int a = 0; a < linearItems.size(); a++) {
                ArrayList<Entry> yVals1 = new ArrayList<Entry>();
                LinearItem linearItem = linearItems.get(a);
                String name = linearItem.getName();
                List<Integer> data = linearItem.getData();
                for (int i = 0; i < data.size(); i++) {
                    int i1 = data.get(i);
                    if (i1 > 1000) {
                        has_K = true;
                    }
                    Entry entry = new Entry(i, i1);
                    entry.setName(name);
                    yVals1.add(entry);
                }
                if (lineChart.getData() != null &&
                        lineChart.getData().getDataSetCount() > 0) {
                    set1 = (LineDataSet) lineChart.getData().getDataSetByIndex(a);
                    set1.setValues(yVals1);
                } else {
                    set1 = new LineDataSet(yVals1, nameGraph);
                    if (a % 2 == 0) {
                        Log.i("TGH", "setData: " + a);
                        set1.setAxisDependency(YAxis.AxisDependency.LEFT);
                    } else {
                        set1.setAxisDependency(YAxis.AxisDependency.RIGHT);

                    }
                    int number = AnalyzeStringUtil.getInstance().getNumber(a);
                    set1.setColor(AnalyzeStringUtil.COLORS[number]);
                    set1.setFillColor(AnalyzeStringUtil.COLORS[number]);
                    set1.setAxisDependency(YAxis.AxisDependency.LEFT);
                    set1.setCircleColor(AnalyzeStringUtil.COLORS[number]);
                    set1.setLineWidth(2f);
                    set1.setCircleRadius(3f);
                    set1.setFillAlpha(65);

                    set1.setHighLightColor(Color.rgb(244, 117, 117));
                    set1.setDrawCircleHole(false);
                    set1.setDrawValues(false);
                    dataSets.add(set1); // add the datasets
                }

            }
            if (lineChart.getData() != null &&
                    lineChart.getData().getDataSetCount() > 0) {
                lineChart.getData().notifyDataChanged();
                lineChart.notifyDataSetChanged();
            } else {
                // create a data object with the datasets
                LineData data = new LineData(dataSets);
                data.setValueTextColor(Color.RED);
                data.setValueTextSize(9f);
                data.setValueFormatter(new LargeValueFormatter());
                // set data
                lineChart.setData(data);
            }
        } else {
            Log.i(TAG, "generateDataLine: linearItems list is null ");
        }

    }

    private String nameGraph = null;

    private void initLineData(AnalyzeResult mAnalyzeResult) {
        if (mAnalyzeResult != null) {
            nameGraph = mAnalyzeResult.getTitleGraph();
            if (nameGraph == null) {
                nameGraph = "";
            }
            getXString(mAnalyzeResult.getxForGraph());
            showIconType(mAnalyzeResult.getyForGraph(), nameGraph);
        }
    }

    private List<String> xForGraph = new ArrayList<>();

    /**
     * 获取X轴数据
     **/
    private void getXString(List<String> xList) {
        if (xList != null && xList.size() > 0) {
            xForGraph = xList;
        } else {
            Log.i(TAG, "getXString: xList is null");
            xForGraph = null;
        }
    }

    private void setLineChart(LineChart tvChannelLineChart) {
        //此方法设置为false时图像拉大后，用手指不能左右上下拖动
        tvChannelLineChart.setDragEnabled(true);
        //去掉图标的标志
        tvChannelLineChart.getDescription().setEnabled(false);
        //禁止水平方向拖拽
        tvChannelLineChart.setScaleXEnabled(true);
        //禁止垂直方向拖拽
        tvChannelLineChart.setScaleYEnabled(false);
        //画图标的边框
        tvChannelLineChart.setDrawBorders(true);
        //设置图标边框的线的宽度
        //tvChannelLineChart.setBorderWidth(2f);
        //设置数据为空时显示的描述文字
        tvChannelLineChart.setNoDataText("暂时没有数据！");
        //设置数据为空时显示的描述文字的颜色
        tvChannelLineChart.setNoDataTextColor(getResources().getColor(R.color.colorPrimaryDark));
        //设置图表的背景颜色 不知道为什么不起作用
        //tvChannelLineChart.setGridBackgroundColor(getResources().getColor(R.color.colorSub));
        //
        //tvChannelLineChart.getYChartMin(false);

        // 设置Legend启用或禁用
        Legend legend = tvChannelLineChart.getLegend();
        legend.setEnabled(false);
        legend.setTextSize(18);
        legend.setTextColor(getResources().getColor(R.color.colorAccent));


        XAxis xAxis = tvChannelLineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f); // only intervals of 1 day
        xAxis.setLabelCount(7);
        xAxis.setValueFormatter(mIAxisValueFormatter_X);
        //设置x轴字体显示角度,即X轴上文字呈现斜着显示
        xAxis.setLabelRotationAngle(0);
        //设置X轴的位置TOP, BOTTOM, BOTH_SIDED, TOP_INSIDE, BOTTOM_INSIDE
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);


        YAxis leftAxis = tvChannelLineChart.getAxisLeft();
        leftAxis.setInverted(false);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        //leftAxis.setAxisMaximum(300f);
        leftAxis.setValueFormatter(mIAxisValueFormatter_Y);
        YAxis rightAxis = tvChannelLineChart.getAxisRight();
        rightAxis.setEnabled(true);
        rightAxis.setInverted(false);
        rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        rightAxis.setValueFormatter(mIAxisValueFormatter_Y_right);

        // get the legend (only possible after setting data)
        Legend l = tvChannelLineChart.getLegend();
        // modify the legend ...
        l.setForm(Legend.LegendForm.LINE);
        // dont forget to refresh the drawing
        tvChannelLineChart.invalidate();
        tvChannelLineChart.animateY(3000);
        //点击显示数据组件
        XYMarkerView mv = new XYMarkerView(this, mIAxisValueFormatter_X);
        mv.setChartView(tvChannelLineChart); // For bounds control
        tvChannelLineChart.setMarker(mv); // Set the marker to the chart

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AnalyzeResultObservable.getInstance().unregisterObserver(this);
    }

    private PopupWindow createPop() {
        View inflate = View.inflate(this, R.layout.hospital_pop, null);
        ListView listView = (ListView) inflate.findViewById(R.id.listview);
        listView.setAdapter(new SingleTextAdapter(this));
        final PopupWindow pop = new PopupWindow(inflate, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        pop.setHeight(200);
        pop.setOutsideTouchable(true);
        pop.setFocusable(true);
        pop.setBackgroundDrawable(new ColorDrawable(0));
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                pop.dismiss();
            }
        });

        pop.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    pop.dismiss();
                    return true;
                }
                return false;
            }
        });
        pop.setBackgroundDrawable(new ColorDrawable(0));
        return pop;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case tv_hospital_details:
                PopupWindow pop = createPop();
                pop.showAsDropDown(tvHospital, 0, 0);
                break;
        }
    }

    /**
     * 无线认证总览昨日关键指标信息I
     */
    private void queryTrendAuthDayYestDayInfo() {
        AnalyzeResultUtil.getInstance(context).queryTrendAuthDayYestDayInfo(summaryInfoListener);
    }

    /**
     * 公众号用户总览昨日关键指标信息
     */
    private void queryTrendUserWxYestDayInfo() {
        AnalyzeResultUtil.getInstance(context).queryTrendUserWxYestDayInfo(summaryInfoListener);
    }

    /**
     * 医院无限认证关键指标接口
     */
    private void queryTrendAuthDayAreaYestDayInfo(String instanceCode) {
        AnalyzeResultUtil.getInstance(context).queryTrendAuthDayAreaYestDayInfo(instanceCode, summaryInfoListener);
    }


    /**
     * 无限认证总览走势图
     */
    private void queryTrendAuthDayGraph(String timeRange) {
        AnalyzeResultUtil.getInstance(this).queryTrendAuthDayGraph(timeRange);
    }

    /**
     * 公众号用户总览走势图
     */
    private void queryTrendUserWxGraph() {
        AnalyzeResultUtil.getInstance(this).queryTrendUserWxGraph(selectViewType + "", selectDate);
    }


    /**
     * 医院无限认证走势图
     */
    private void queryTrendAuthDayAreaGraph() {
        AnalyzeResultUtil.getInstance(context).queryTrendAuthDayAreaGraph(selectViewType + "", selectHospitalCode, selectDate);
    }


    DataHandler handler = new DataHandler(this);

    private static class DataHandler extends Handler {
        /**
         * 昨日关键指标信息
         */
        private final int QueryTrendAuthDayYestDayInfo = 0x001;
        /**
         * 走势图
         */
        private final int QueryTrend = 0x002;

        WeakReference<WirelessAuthenticationLineChart> reference;

        private DataHandler(WirelessAuthenticationLineChart activity) {
            reference = new WeakReference<WirelessAuthenticationLineChart>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            WirelessAuthenticationLineChart activity = reference.get();
            if (activity != null) {
                switch (msg.what) {
                    case QueryTrendAuthDayYestDayInfo:
//                        if (activity.viewType.equals("1")) {
//                            activity.queryTrendAuthDayYestDayInfo();
//                        } else if (activity.viewType.equals("2")) {
//                            activity.queryTrendUserWxYestDayInfo(); //公众号用户总览昨日关键指标信息
//                        } else if (activity.viewType.equals("3")) {
//                            activity.queryTrendAuthDayAreaYestDayInfo(activity.selectHospitalCode);
//                        }

                        switch (activity.viewType) {
                            case "1":
                                activity.queryTrendAuthDayYestDayInfo();
                                break;
                            case "2":
                                activity.queryTrendUserWxYestDayInfo(); //公众号用户总览昨日关键指标信息
                                break;
                            case "3":
                                activity.queryTrendAuthDayAreaYestDayInfo(activity.selectHospitalCode);
                                break;
                        }
                        break;

                    case QueryTrend:
                        if (activity.viewType.equals("1")) {
                            activity.queryTrendAuthDayGraph(activity.selectDate);
                            activity.queryTrendAuthDayList();
                        } else if (activity.viewType.equals("2")) {
                            activity.queryTrendUserWxGraph();
                            activity.queryTrendUserWxList();
                        } else if (activity.viewType.equals("3")) {
                            activity.queryTrendAuthDayAreaGraph();
                            activity.queryTrendAuthDayAreaList();
                        }
                        break;
                }
            }
        }
    }

    class WifiExpandableListView extends BaseExpandableListAdapter {
        @Override
        public int getGroupCount() {
            int count = 0;
            if (groupTime != null) {
                count = groupTime.size();
            }
            return count;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            int count = 0;
            if (childDataMap != null) {
                String s = groupTime.get(groupPosition);
                count = childDataMap.get(s).size();
            }
            return count;
        }

        @Override
        public Object getGroup(int groupPosition) {
            return groupTime.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return childDataMap.get(groupTime.get(groupPosition));
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            View inflate = View.inflate(context, R.layout.text_adapter, null);
            TextView tv = (TextView) inflate.findViewById(R.id.tv_week);
            tv.setText("\t\t\t\t\t" + groupTime.get(groupPosition));
            tv.setTextColor(context.getResources().getColor(R.color.colorTextMinor));
            return inflate;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            View inflate = View.inflate(context, R.layout.text_chirld_adapter, null);
            TextView tv = (TextView) inflate.findViewById(R.id.tv_week);
            TextView tvValue = (TextView) inflate.findViewById(R.id.tv_week_value);
            String s = groupTime.get(groupPosition);
            List<String> strings = childDataMap.get(s);
            String s1 = strings.get(childPosition);
            String[] split = s1.split(":");
            if (split.length == 2) {
                tv.setText(split[0]);
                tvValue.setText(split[1]);
            }
            tv.setTextSize(15);
            tv.setTextColor(context.getResources().getColor(R.color.colorTextHint));
            return inflate;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }
    }
}
